package com.dean.ui.panel.impl;

import com.dean.action.ExcelOptAction;
import com.dean.constants.DeanUiConstants;
import com.dean.entity.DeanImportInfo;
import com.dean.entity.DeanResponse;
import com.dean.entity.SysDbConnInfo;
import com.dean.service.DbConnService;
import com.dean.ui.panel.DeanPanel;
import com.dean.ui.utils.UiUtils;
import com.dean.utils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDateTime;
import java.util.Properties;

/**
 * @ClassName ExcelImpExpPanel
 * @Description excel导入导出页面布局
 * @Author dean
 * @Date 2021/10/3 10:03
 */
public class ExcelImpExpPanel extends BasePanel implements DeanPanel {

    private static final Logger logger = LoggerFactory.getLogger(ExcelImpExpPanel.class);

    private final String INIT_PATH_NAME = DeanUiConstants.INIT_PATH + "excel.properties";

    private JLabel connNameLable;
    private JComboBox<String> connName;

    private JLabel filePathLable;
    private JTextField filePath;
    
    private JTextArea fields;

    private JTextArea exeLog;
    private JTextField executeRes;

    private JLabel commitNumLabel;
    private JTextField commitNum;
    private JLabel tableNameLabel;
    private JTextField tableName;
    private JButton saveCfgBtn;
    private JButton exportBtn;
    private JButton importBtn;

    @Override
    public void mainUi() {
        int rowCount = 1;

        connNameLable = new JLabel("connName:");
        UiUtils.setRightBounds(connNameLable,rowCount);
        panel.add(connNameLable);

        connName = new JComboBox<String>();
        UiUtils.setRightBounds(connName,rowCount);
        panel.add(connName);
        rowCount++;

        //文件地址
        filePathLable = new JLabel("请输入文件路径:");
        UiUtils.setRightBounds(filePathLable,rowCount);
        panel.add(filePathLable);

        filePath = new JTextField();
        UiUtils.setRightBounds(filePath,rowCount);
        panel.add(filePath);

        rowCount++;

        tableNameLabel = new JLabel("TABLENAME:");
        UiUtils.setRightBounds(tableNameLabel,rowCount);
        panel.add(tableNameLabel);

        tableName = new JTextField();
        UiUtils.setRightBounds(tableName,rowCount);
        panel.add(tableName);
        rowCount++;

        commitNumLabel = new JLabel("commitNum:");
        UiUtils.setRightBounds(commitNumLabel,rowCount);
        panel.add(commitNumLabel);

        commitNum = new JTextField("4000");
        UiUtils.setRightBounds(commitNum,rowCount);
        panel.add(commitNum);
        rowCount++;

        // sql输入窗口
        fields = new JTextArea("data_id,dfzh,dfhm,dfxh,dfxm");
        JScrollPane sqlInput = new JScrollPane(fields);
        UiUtils.setTextAreaBounds(fields,1,5,1);
        UiUtils.setTextAreaBounds(sqlInput,1,5,1);
        panel.add(sqlInput);

        saveCfgBtn = new JButton("保存配置信息");
        UiUtils.setRightButtonBounds(saveCfgBtn,rowCount,1);
        panel.add(saveCfgBtn);

        exportBtn = new JButton("导出EXCEL");
        UiUtils.setRightButtonBounds(exportBtn,rowCount,2);
        panel.add(exportBtn);

        // 执行按钮
        importBtn = new JButton("导入EXCEL");
        UiUtils.setRightButtonBounds(importBtn,rowCount,3);
        panel.add(importBtn);

        rowCount++;

        exeLog = new JTextArea();
        JScrollPane exeLogPane = new JScrollPane(exeLog);
        exeLog.setEnabled(false);
        exeLog.setText("使用说明:\n" +
                "1.excel导入 \n" +
                "1.1 需要指定表的字段名 会根据字段名匹配excel中的表头信息 匹配不上则不进行导入 \n" +
                "1.2 注意建表时需要创建remark字段,程序会将文件名称和sheet名称存入remark字段 \n" +
                "1.3 指定的文件目录下不要存放多余的excel文件否则会默认读取进行字段匹配,虽然字段匹配不上,但是会浪费时间 \n" +
                "1,4 每次提交的记录数请根据服务的实际情况调整 \n" +
                "1.5 导入时需要指定导入的表名 \n" +
                "2.excel导出 \n" +
                "2.1 需要输入sql语句用【;】进行sql语句分割 \n" +
                "2.2 指定导出的文件路径 \n" +
                "2.3 如果需要指定对应sql导出的文件名称可以参考如下配置: \n" +
                "    select * from tb_user ### user_list.xlsx \n" +
                "2.4 如果不指定文件名称则采用uuid 命名 \n" +
                "2.5 导出是并发执行的，如果需要知道哪些文件导出请查看日志 \n");

        UiUtils.setTextAreaBounds(exeLogPane,rowCount,-1,1,2);
        UiUtils.setTextAreaBounds(exeLog,rowCount,-1,1,2);

        panel.add(exeLogPane);
    }

    @Override
    public void mainScript() {
        // 加载配置文件
        initProperties();
        exportBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                excelExp();
            }
        });

        importBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                excelImp();
            }
        });

        // 下拉框处理
        DbConnService.getInstance().getConnInfos().forEach(connInfo -> {
            logger.debug(connInfo.getConnName());
            connName.addItem(connInfo.getConnName());
        });

        saveCfgBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (saveProperties()) {
                    JOptionPane.showMessageDialog(panel, "配置信息保存成功", "SUCESS", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(panel, "配置信息保存失败", "ERROR", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

    }

    private void excelExp() {
        String fileDir = filePath.getText();
        if (fileDir == null || "".equals(fileDir)) {
            JOptionPane.showMessageDialog(panel, "请输入文件导出目录", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        String exeSql = fields.getText();
        if (exeSql == null || "".equals(exeSql)) {
            JOptionPane.showMessageDialog(panel, "执行sql不能为空", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (!exeSql.trim().toLowerCase().startsWith(DeanUiConstants.START_SELECT_CHAR)) {
            JOptionPane.showMessageDialog(panel, "非法sql，不允许执行", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        String[] exeSqls = exeSql.replaceAll("\n", "").split(";");
        logger.debug("执行开始时间:" + LocalDateTime.now());
        ExcelOptAction optAction = ExcelOptAction.getInstance();
        DeanResponse deanResponse = optAction.exportExcel(initDbConnect(),fileDir,exeSqls);
        if(deanResponse.getCode() == 0){
            JOptionPane.showMessageDialog(panel, deanResponse.getMsg(), "SUCCESS", JOptionPane.INFORMATION_MESSAGE);
        }else{
            JOptionPane.showMessageDialog(panel, deanResponse.getMsg(), "ERROR", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void excelImp() {
        // 获取执行参数
        String exeParams = fields.getText();
        if (exeParams == null || "".equals(exeParams)) {
            JOptionPane.showMessageDialog(panel, "获取字段信息失败", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        String fileDir = filePath.getText();
        if(fileDir == null || "".equals(fileDir)){
            JOptionPane.showMessageDialog(panel, "导入文件地址不能为空", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        String[] fields = exeParams.split(",");
        ExcelOptAction excelOptAction = ExcelOptAction.getInstance();
        DeanResponse deanResponse = excelOptAction.importExcel(initDbConnect(),fileDir, initImportInfo(fields));
        if(deanResponse.getCode() == 0){
            JOptionPane.showMessageDialog(panel, deanResponse.getMsg(), "SUCCESS", JOptionPane.INFORMATION_MESSAGE);
        }else{
            JOptionPane.showMessageDialog(panel, deanResponse.getMsg(), "ERROR", JOptionPane.ERROR_MESSAGE);
        }
    }



    /**
     * 保存配置文件
     *
     * @return
     */
    private boolean saveProperties() {
        Properties properties = new Properties();
        // 读取 接口地址 dbDriver dbUrl dbUsername dbPassword
        properties.setProperty("connName", connName.getSelectedItem().toString());
        properties.setProperty("commitNum", commitNum.getText());
        properties.setProperty("tableName", tableName.getText());
        properties.setProperty("filePath", filePath.getText());
        properties.setProperty("fields", fields.getText());
        return PropertyUtils.saveProperties(INIT_PATH_NAME, properties);
    }

    /**
     * 初始化功能配置
     */
    @Override
    public void initProperties() {
        //初始化基础参数
        Properties properties = PropertyUtils.readProperties(INIT_PATH_NAME);
        if (properties != null) {
            connName.setSelectedItem(properties.getProperty("connName"));
            commitNum.setText(properties.getProperty("commitNum"));
            tableName.setText(properties.getProperty("tableName"));
            filePath.setText(properties.getProperty("filePath"));
            fields.setText(properties.getProperty("fields"));
        }
    }

    /**
     * 设置数据库连接配置
     */
    private SysDbConnInfo initDbConnect() {
        SysDbConnInfo connectInfo = new SysDbConnInfo();
        connectInfo.setConnName(connName.getSelectedItem().toString());
        return connectInfo;
    }

    /**
     * 导入需要的信息
     * @param fields
     * @return
     */
    private DeanImportInfo initImportInfo(String [] fields){
        DeanImportInfo importInfo = new DeanImportInfo();
        importInfo.setFields(fields);
        importInfo.setTableName(tableName.getText());
        importInfo.setCommitNums(Integer.parseInt(commitNum.getText()));
        return importInfo;
    }

}
